<!DOCTYPE html>
<html lang="ch-CN">
<head>
  <meta charset="UTF-8">
  <title>鼠标实时位置</title>
</head>
<style>
  body {
    width: 100%;
    height: 100vh;
    background-color: wheat;
    font-size: 30px;
    /*文本透明*/
    /*text-decoration: none;*/
    font-family: "华文楷体";
    display: flex;
    flex-direction: column;
    /*justify-content: center;*/
    align-items: center;
  }

  p {
    font-size: 40px;
    margin: 20px 0 0 0;
    font-weight: bold;
  }

  span {
    /*display: block;*/
    line-height: 50px;
  }
  #box1{
    width: 500px;
    height: 300px;
    background-color: #b3b1af;
    border: solid 1px black;
  }
  #box2{
    margin-top: 50px;
    width: 500px;
    height: 150px;
    background-color: khaki;
    border: solid 1px black;
    text-align: center;
  }

</style>
<body>
<div id="box1"></div>
<div id="box2">
  <p>指针离盒子的位置</p>
</div>
</body>
<!--
      event.clientX等不适用于有滚动条的页面中
      一般页面更适合使用pageX
-->
<script>
let box1=document.getElementById("box1")
let box2=document.getElementById("box2")
let index_X=document.createElement("p")
let index_Y=document.createElement("p")
index_X.style.margin="0"
index_Y.style.margin="0"
index_X.style.fontWeight="none"
index_Y.style.fontWeight="none"
index_X.style.fontSize="30px"
index_Y.style.fontSize="30px"
box2.appendChild(index_X)
box2.appendChild(index_Y)

box1.onmousemove=function (event){
  index_X.innerHTML="离盒子左侧距离："+event.offsetX
  index_Y.innerHTML="离盒子顶部距离："+event.offsetY
}


</script>
</html>